<?php
$tmpPath = '/../../..';
if (!file_exists(dirname(__FILE__).$tmpPath.'/wp-config.php')) {
$tmpPath = '/../../../..';
    if (!file_exists(dirname(__FILE__).$tmpPath.'/wp-config.php')) {
        echo "Error: wp-config.php not found";
        exit;
    }
}
if (!isset($_GET['module']) ) {
    exit;
}
require_once(dirname(__FILE__).$tmpPath.'/wp-config.php');
require_once(dirname(__FILE__).$tmpPath.'/wp-admin/admin-functions.php');
require_once(dirname(__FILE__).$tmpPath.'/wp-admin/admin-db.php');

get_currentuserinfo();

if ( !current_user_can('manage_categories') )
	die('-1');

function get_out_now() { exit; }
add_action('shutdown', 'get_out_now', -1);

require_once(dirname(__FILE__).'/tantan_reports_graphs.php');
function getCache($cacheID) {
    $cacheTimeout = get_option('tantan_gaCacheT_'.$cacheID);
    if ($cacheTimeout && (time() - $cacheTimeout < 3600)) {
        return get_option('tantan_gaCacheD_'.$cacheID);
    } else {
        return false;
    }    
}
function updateCache($cacheID, $value) {
    update_option('tantan_gaCacheT_'.$cacheID, time());
    update_option('tantan_gaCacheD_'.$cacheID, $value);
    return $value;
}
?>
<html>
<head>
<style type="text/css">
@import url(tantan_reports.css);
<?php if (!$_GET['load']):?>
body {
    background:white url(loading.gif) no-repeat center;
    height:100%;
}
<?php endif; ?>
</style>
<?php if (!$_GET['load']):
$url = "tantan_reports_load.php?load=1&module=".$_GET['module']."&report=".$_GET['report'];
?>
<script type="text/javascript">
function showReport() {
window.location.replace('<?php echo $url;?>');
}
window.onload = function() {
    setTimeout('showReport()', 300);
}
</script>
<?php endif;?>

</head>
<body>
<?php
if ($_GET['load']) {
$start = date('Ymd', time() - 604800);
$stop  = date('Ymd', time() - 86400);
if ($_GET['module'] == 'analytics') {
    require_once(dirname(__FILE__).'/lib.googleanalytics.php');
    $siteProfile    = get_option('tantan_gaSiteProfile');
    $session        = get_option('tantan_gaSession');
    $ga = new tantan_GoogleAnalytics();
    $ga->setSession($session);
    
    switch ($_GET['report']) {
        case 'gainingcontent':
            if (!($data = getCache('content'))) {
                $data = updateCache('content', $ga->getReport($siteProfile, $start, $stop, 'content'));
            }
            
            foreach ($data['Top Content']['records'] as $k => $record) {
                if ($record['Uniq. Views(2)'] >= 0 && !ereg('http://', $record['Content']) && !ereg('^/outgoing/', $record['Content'])) {
                    $data['Top Content']['records'][$k]['Change'] = $record['Uniq. Views'] - $record['Uniq. Views(2)'];//round($record['Uniq. Views'] / $record['Uniq. Views(2)'], 2);
                } else {
                    $data['Top Content']['records'][$k]['Change'] = 0;
                }
            }
            usort($data['Top Content']['records'], create_function('$a,$b', 'if ($a[Change] == $b[Change]) return 0; return ($a[Change] < $b[Change]) ? 1 : -1;'));
            $gainMax = 0;
            for ($i=0;$i<5;$i++) {
                $gainMax = max($data['Top Content']['records'][$i]['Uniq. Views'], $gainMax);
            }
            printHorizGraph('Rising Content', $data['Top Content']['records'], $gainMax, 'Uniq. Views', 'Content', 'Content with the most net gain of unique views');
        break;
        case 'fallingcontent':
            if (!($data = getCache('content'))) {
                $data = updateCache('content', $ga->getReport($siteProfile, $start, $stop, 'content'));
            }
            
            foreach ($data['Top Content']['records'] as $k => $record) {
                if ($record['Uniq. Views(2)'] >= 0 && !ereg('http://', $record['Content']) && !ereg('^/outgoing/', $record['Content'])) {
                    $data['Top Content']['records'][$k]['Change'] = $record['Uniq. Views'] - $record['Uniq. Views(2)'];//round($record['Uniq. Views'] / $record['Uniq. Views(2)'], 2);
                } else {
                    $data['Top Content']['records'][$k]['Change'] = 0;
                }
            }
            usort($data['Top Content']['records'], create_function('$a,$b', 'if ($a[Change] == $b[Change]) return 0; return ($a[Change] < $b[Change]) ? -1 : 1;'));
            $gainMax = 0;
            for ($i=0;$i<5;$i++) {
                $gainMax = max($data['Top Content']['records'][$i]['Uniq. Views'], $gainMax);
            }
            printHorizGraph('Falling Content', $data['Top Content']['records'], $gainMax, 'Uniq. Views', 'Content', 'Content with the most net loss of unique views');
        
        break;
        case 'visits':
        case 'pageviews':
        case 'avgpageviews':
            if (!($data = getCache('visitspageviews'))) {
                $data = updateCache('visitspageviews', $ga->getReport($siteProfile, $start, $stop, 'visitspageviews'));
            }
            if     ($_GET['report'] == 'visits')       printVertGraph('Daily Visits', $data['Visits']['records'], $data['Visits']['MaxVisits'], 'Date Range', 'Visits', 'Number of people that visited your site');
            elseif ($_GET['report'] == 'pageviews')    printVertGraph('Daily Pageviews', $data['Pageviews']['records'], $data['Pageviews']['MaxPageviews'], 'Date Range', 'Pageviews', 'How many pages were viewed');
            elseif ($_GET['report'] == 'avgpageviews') printVertGraph('Avg Pageviews per Visit', $data['Average Pageviews per Visit']['records'], $data['Average Pageviews per Visit']['MaxP/Visit'], 'Date Range', 'P/Visit', 'Average number of pageviews per visit');
        break;
        case 'gaininginbound':
        if (!($data = getCache('referals'))) {
            $data = updateCache('referals', $ga->getReport($siteProfile, $start, $stop, 'referals'));
        }
        foreach ($data['Referring Source']['records'] as $k => $record) {
            if ($record['Visits(2)'] >= 0) {
                $data['Referring Source']['records'][$k]['Change'] = $record['Visits'] - $record['Visits(2)'];
            } else {
                $data['Referring Source']['records'][$k]['Change'] = 0;
            }
        }
        usort($data['Referring Source']['records'], create_function('$a,$b', 'if ($a[Change] == $b[Change]) return 0; return ($a[Change] < $b[Change]) ? 1 : -1;'));
        $gainMax = 0;
        for ($i=0;$i<5;$i++) {
            $gainMax = max($data['Referring Source']['records'][$i]['Visits'], $gainMax);
        }
        printHorizGraph('Rising Sources', $data['Referring Source']['records'], $gainMax, 'Visits', 'Source [Medium]', 'Sources with the most net gain referrals');
        break;
        case 'inbound':
            if (!($data = getCache('referals'))) {
                $data = updateCache('referals', $ga->getReport($siteProfile, $start, $stop, 'referals'));
            }
            printHorizGraph('Inbound Sources', $data['Referring Source']['records'], $data['Referring Source']['MaxVisits'], 'Visits', 'Source [Medium]', 'Where did people find your site');
        break;
        case 'outbound':
            if (!($data = getCache('outbound'))) {
                $data = updateCache('outbound', $ga->getReport($siteProfile, $start, $stop, 'outbound'));
            }
            printHorizGraph('Outbound Links', $data['Top Content']['records'], $data['Top Content']['MaxUniq. Views'], 'Uniq. Views', 'Content', 'External sites people went to from your site');
        break;
        case 'popular':
            if (!($data = getCache('content'))) {
                $data = updateCache('content', $ga->getReport($siteProfile, $start, $stop, 'content'));
            }
            printHorizGraph('Popular Content', $data['Top Content']['records'], $data['Top Content']['MaxUniq. Views'], 'Uniq. Views', 'Content', 'Most popular content on your site');
        break;
        case 'entry':
            if (!($data = getCache('entrance'))) {
                $data = updateCache('entrance', $ga->getReport($siteProfile, $start, $stop, 'entrance'));
            }
            printHorizGraph('Entry Pages', $data['Entrance Bounce Rates']['records'], $data['Entrance Bounce Rates']['MaxEntrances'], 'Entrances', 'Top Entrances','First page people visit on your site');
        break;
        case 'newreturn':
            if (!($data = getCache('executive'))) {
                $data = updateCache('executive', $ga->getReport($siteProfile, $start, $stop, 'executive'));
            }
            $totalVisits = ((int) $data['Visits by New and Returning']['records'][0]['Visits'] + (int) $data['Visits by New and Returning']['records'][1]['Visits']);
            if ($totalVisits > 0) {
                $newVisits = round(($data['Visits by New and Returning']['records'][0]['Visits'] / $totalVisits) * 100, 2);
                $retVisits = round(($data['Visits by New and Returning']['records'][1]['Visits'] / $totalVisits) * 100, 2);
            } else {
                $newVisits = 0;
                $retVisits = 0;
            }
            printFiftyFiftyGraph('New &amp; Returning', $newVisits, $retVisits, 'New', 'Returning', 'Percentage of new and returning visitors');
        break;
        case '7dayreport':
            if (!($data = getCache('visitspageviewscompare'))) {
                $data = updateCache('visitspageviewscompare', $ga->getReport($siteProfile, $start, $stop, 'visitspageviewscompare'));
            }

            $visitsNow = 0;
            $visitsPast = 0;
            if ($siteProfile) {
                if (is_array($data['Visits']['records'])) foreach ($data['Visits']['records'] as $visit) {
                    $visitsNow += $visit['Visits'];
                    $visitsPast += $visit['Visits(2)'];
                }
                if ($visitsPast > 0) {
                    $visitsPercent = round(($visitsNow / $visitsPast),2);
                } else {
                    $visitsPercent = 1;
                }
                if ($visitsPercent >= 1) {
                    $visitsPercentLabel = '<span class="plus">(+'.(($visitsPercent * 100)-100).'%)</span> ';
                } else {
                    $visitsPercentLabel = '<span class="minus">('.(($visitsPercent * 100)-100).'%)</span> ';
                }
                
                
                $viewsNow = 0;
                $viewsPast = 0;
                if (is_array($data['Pageviews']['records'])) foreach ($data['Pageviews']['records'] as $view) {
                    $viewsNow += $view['Pageviews'];
                    $viewsPast += $view['Pageviews(2)'];
                }
                if ($viewsPast > 0) {
                    $viewsPercent = round($viewsNow / $viewsPast, 2);
                } else {
                    $viewsPercent = 1;
                }
                if ($viewsPercent >= 1) {
                    $viewsPercentLabel = '<span class="plus">(+'.(($viewsPercent * 100)-100).'%)</span> ';
                } else {
                    $viewsPercentLabel = '<span class="minus">('.(($viewsPercent * 100)-100).'%)</span> ';
                }
                    
            }
            echo '<p>During the past 7 days, your site received <strong>'.number_format($visitsNow).'</strong> visitors ' .$visitsPercentLabel. ' and <strong>' .number_format($viewsNow). '</strong> pageviews ' .$viewsPercentLabel. '.</p>';

        break;
    }
} elseif ($_GET['module'] == 'feedburner') {
    require_once(dirname(__FILE__).'/lib.feedburner.php');
    $fb    = new tantan_Feedburner();
    $fbURI = get_option('tantan_fbURI');
    $data = $fb->getFeedData($_GET['report'], $start, $stop);
    printVertGraph('Circulation <small>- '.$_GET['report'].'</small>', $data['records'], $data['MaxCirculation'], 'Date Label', 'Circulation', 'Number of subscribers to your content');
} 
} // loading

?>

</body>
</html>